Imports System.Threading
Imports System.Data.OleDb
Public Class clsApp
    Const Sync As String = "_"
    Private appName As String
    Private appPath As String
    Private dataPath As String
    Private pluginPath As String
    Private stylesPath As String
    Private selectedStyle As String = Nothing
    Private verMajor As Int32
    Private verMinor As Int32
    Private verPatch As Int32
    Private verStage As String
    Private sAdArr() As String
    Private sAdLinkArr() As String
    Private dbCon As OleDbConnection
    Private bCreateData As Boolean = False
    Private bPluginsExists As Boolean = False
    'Private adoConnection As ADODB.Connection = New ADODB.Connection
    'Public isReady As Boolean = False

    Public Event ComponentLoading(ByVal data As String)
    Public Event STIMPyLoaded()
    Private Delegate Sub NoParamDlg()
    Public Sub New(ByVal Version As String) ', ByRef Splash As FormSplash)
        AppNewThread = Thread.CurrentThread
        'MsgBox("App.New()")
        If Thread.CurrentThread.Name Is Nothing Then Thread.CurrentThread.Name = "clsApp.New"
        SyncLock Me.Sync
            If bSplash Then
                AddHandler ComponentLoading, AddressOf frmSplash.changeStatus
                AddHandler STIMPyLoaded, AddressOf frmSplash.tmrSplash.Start
            End If
            RaiseEvent ComponentLoading("Getting Path Information...")
            appPath = System.Windows.Forms.Application.StartupPath
            'MsgBox(appPath)
            dataPath = appPath + "\data\"
            pluginPath = appPath + "\plugins\"
            Me.stylesPath = appPath + "\styles\"
            'Check for data folder
            Dim fso As Scripting.FileSystemObject = New Scripting.FileSystemObject
            If Not fso.FolderExists(Me.dataPath) Then
                frmSplash.pbSplash.Maximum += 20
                RaiseEvent ComponentLoading("Creating Codename: STIMPy! File Structure...")
                fso.CreateFolder(Me.dataPath)
            End If
            'check for plugin folder
            If Not fso.FolderExists(Me.pluginPath) Then
                fso.CreateFolder(Me.pluginPath)
            Else 'If plugin  folder exists, look for plugins
                Dim files() As System.IO.FileInfo
                Dim dir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(Me.pluginPath)
                files = dir.GetFiles("*.dll")
                If files.GetUpperBound(0) > 0 Then Me.bPluginsExists = True
            End If
            If Not fso.FolderExists(Me.stylesPath) Then
                fso.CreateFolder(Me.stylesPath)
                If Not fso.FolderExists(Me.stylesPath + "full\") Then fso.CreateFolder(Me.stylesPath + "full\")
                If Not fso.FolderExists(Me.stylesPath + "sounds\") Then fso.CreateFolder(Me.stylesPath + "sounds\")
                If Not fso.FolderExists(Me.stylesPath + "skins\") Then fso.CreateFolder(Me.stylesPath + "skins\")
            End If
            frmMain.playSound(Me.SoundPath + "StartUp")
            'Getting Version Number...
            RaiseEvent ComponentLoading("Getting Version Number...")
            verMajor = CType(Version.Substring(0, Version.IndexOf(".")), Int32)
            verMinor = CType(Version.Substring(verMajor.ToString.Length + 1, _
            Version.IndexOf(".", verMajor.ToString.Length + 1)), Int32)
            verPatch = CType(Version.Substring(verMinor.ToString.Length _
                + verMajor.ToString.Length + 2, Version.IndexOf(" ") _
                - verMinor.ToString.Length - verMajor.ToString.Length - 2), Int32)
            verStage = Version.Substring(Version.IndexOf(" ") + 1)
            'Getting Process Information...
            RaiseEvent ComponentLoading("Getting Process Information...")
            appName = Process.GetCurrentProcess.ProcessName()
            'Getting Path Information...
            'Looking For A Previously Running Version...
            RaiseEvent ComponentLoading("Looking For A Previously Running Version...")
            'If Me.PrevInstance Then
            'MsgBox("You may only run STIMPy! once per system!", MsgBoxStyle.OKOnly, _
            '       "STIMPy!")
            'sktMain.Close()
            'Application.Exit()
            'End If
            'check to see if STIMPy.dat is present in the data dir. if not, create it
            If Not fso.FileExists(Me.dataPath + "STIMPy.dat") Then
                frmSplash.pbSplash.Maximum += 20
                RaiseEvent ComponentLoading("Creating Codename: STIMPy! Data Files...")
                Dim adoCat As ADOX.Catalog = New ADOX.Catalog
                adoCat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Me.dataPath + "STIMPy.dat")
                Dim adoTable As ADOX.Table = New ADOX.Table
                adoTable.Name = "tblUsers"
                adoTable.Columns.Append("UserId", ADOX.DataTypeEnum.adDouble, 2)
                adoTable.Columns.Append("Username", ADOX.DataTypeEnum.adVarChar, 25)
                adoTable.Columns.Append("Password", ADOX.DataTypeEnum.adVarChar, 40)
                adoTable.Columns.Append("AutoLog", ADOX.DataTypeEnum.adBinary)
                adoCat.Tables.Append(adoTable)
                Dim adoIndex As ADOX.Index = New ADOX.Index
                adoIndex.Name = "UID"
                adoIndex.Columns.Append("UserId")
                adoTable.Indexes.Append(adoIndex)
                adoTable = Nothing
                adoTable = New ADOX.Table
                adoTable.Name = "Messages"
                adoTable.Columns.Append("UserId", ADOX.DataTypeEnum.adTinyInt)
                adoTable.Columns.Append("From", ADOX.DataTypeEnum.adVarChar, 25)
                adoTable.Columns.Append("Message", ADOX.DataTypeEnum.adVarChar, 250)
                adoCat.Tables.Append(adoTable)
                adoTable = Nothing
                adoIndex = Nothing
                adoCat = Nothing
                Me.bCreateData = True
            End If
            dbCon = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Me.dataPath + "STIMPy.dat")
            If Not dbCon Is Nothing Then
                dbCon.Open()
                'do Setup Code
                'Dim dbcom As OleDbCommand = dbCon.CreateCommand()

                'dbcom.CommandText = _
                '  "CREATE TABLE tblUserInfo (" _
                '  + "Userid      AutoNumber," _
                '  + "Username     Text(25)," _
                '  + "Password     Text(40) NULL);"
                '  '+ "AutoLogin    Bit DEFAULT 0);" ' _
                '  '+ "CONSTRAINT uid_primaryKey PRIMARY KEY(user_id));"
                ''dbcom.Connection = dbCon
                'dbcom.ExecuteNonQuery()
            Else
                MsgBox("Unable to create the database in the data directory." + vbNewLine _
                  + "Codename: STIMPy! will try again next time you load the program." + vbNewLine _
                  + "Until then, the User options and Login options will not save correctly." + vbNewLine _
                  + "If this problem persists, please visit http://www.codenamestimpy.com")
            End If
            'dbCon.Close()
            'dbCon.Dispose()
            'dbCon = Nothing

            frmSplash.pbSplash.Maximum += 20
            RaiseEvent ComponentLoading("Loading plugins for Codename: STIMPy!...")



            'Checking for Update...
            RaiseEvent ComponentLoading("Checking for Update...")
            '!'Application.DoEvents() '--Added in until a function can be made
            Update()
            Thread.CurrentThread.Suspend()
            'RaiseEvent ComponentLoading("Program is up to date")
            'If program needs updating, run updater

            'RaiseEvent ComponentLoading("Starting Updater...")
            'MsgBox("App resumed")

            Application.DoEvents() '--Added in until a function can be made
            ' Run Update Application
            ' Kill this app

            ' application.Exit




            'All Done...
            Dim dlg As New NoParamDlg(AddressOf frmSplash.tmrSplash.Start)
            frmSplash.Invoke(dlg)

            RaiseEvent STIMPyLoaded()
            Application.DoEvents()
            '-- Not sure if this is working, should be able
            '-- to accomplish the same thing with the
            '-- event STIMPyLoaded()
            'frmSplash.tmrSplash.Start()
            If frmSplash.tmrSplash.Enabled = False Then
                frmSplash.tmrSplash.Enabled = True
            End If
        End SyncLock
    End Sub
    Protected Overrides Sub Finalize()
        appName = Nothing
        appPath = Nothing
        verMajor = Nothing
        verMinor = Nothing
        verPatch = Nothing
        verStage = Nothing
        ReDim sAdArr(0)
        sAdArr = Nothing
        ReDim sAdLinkArr(0)
        sAdLinkArr = Nothing
        If Not dbCon Is Nothing Then
            dbCon.Close()
            dbCon = Nothing
        End If
    End Sub
    Public Sub Close()
        Me.Finalize()
    End Sub
    Public ReadOnly Property PrevInstance() As Boolean
        Get
            Dim sameProcessTotal As Integer = Process.GetProcessesByName(appName).Length
            If sameProcessTotal > 1 Then
                PrevInstance = True
            End If
        End Get
    End Property
    Public ReadOnly Property GetPath() As String
        Get
            GetPath = appPath
        End Get
    End Property
    Public ReadOnly Property GetMajor() As Int32
        Get
            GetMajor = verMajor
        End Get
    End Property
    Public ReadOnly Property GetMinor() As Int32
        Get
            GetMinor = verMinor
        End Get
    End Property
    Public ReadOnly Property GetPatch() As Int32
        Get
            GetPatch = verPatch
        End Get
    End Property
    Private ReadOnly Property isUpToDate() As Boolean
        Get

        End Get
    End Property
    Public Sub Update()
        Do Until sktMain.Connected
            Application.DoEvents()
        Loop
        sktMain.Send("VERSION_" + VERSION)
    End Sub
    Public ReadOnly Property GetStage() As String
        Get
            GetStage = verStage
        End Get
    End Property
    Public ReadOnly Property GetName() As String
        Get
            GetName = appName
        End Get
    End Property
    Public ReadOnly Property SoundPath() As String
        Get
            Return Me.stylesPath + IIf(Me.selectedStyle Is Nothing, "sounds\", "full\" + Me.selectedStyle + "\sounds\")
        End Get
    End Property
    Public Sub InsertUserInfo(ByVal username As String, ByVal password As String, ByVal autoLog As Boolean)
        'Dim dbcom As OleDb.OleDbCommand = dbCon.CreateCommand
        'dbcom.CommandText = "SELECT Username FROM tblUsers WHERE Username=" & username
        'Dim dbReader As OleDb.OleDbDataReader
        'dbReader = dbcom.ExecuteReader()
        'If dbReader.HasRows Then
        'dbReader.Close()
        'dbcom.CommandText = "UPDATE Users SET Password='" + password + "'" + _
        '  "WHERE Username='" + username + "'"


        'End If
    End Sub
End Class